/*
 * Copyright (C) 2011, 2012 Moravská zemská knihovna v Brně / Moravian Library in Brno
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.oai.provider.response;

import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.Identifier;
import cz.mzk.oai.metadataRepository.repository.Repository;
import cz.mzk.oai.metadataRepository.repository.records.Record;
import cz.mzk.oai.provider.ErrorCode;
import cz.mzk.oai.provider.OaiException;
import cz.mzk.oai.provider.tools.ElementAppender;
import cz.mzk.oai.provider.tools.Parser;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class GetRecord extends OaiVerbResponse {

    private final String IDENTIFIER = "identifier";
    private final String METADATA_PREFIX = "metadataPrefix";

    public GetRecord(Map<String, String[]> parameters, String baseUrl) throws IOException {
        super("GetRecord", parameters, baseUrl);
    }

    @Override
    String[] getRequiredArguments() {
        String[] result = {IDENTIFIER, METADATA_PREFIX};
        return result;
    }

    @Override
    String[] getOptionalArguments() {
        String[] result = {};
        return result;

    }

    @Override
    String getExclusiveArgument() {
        return null;
    }

    @Override
    void createResponse() throws OaiException, IOException {
        String idString = getArgumentValueIfPresent(IDENTIFIER);
        Identifier id = Parser.parseIdentifier(idString);
        String metadataPrefix = getArgumentValueIfPresent(METADATA_PREFIX);
        MetadataFormat format = Parser.parseMetadataPrefix(metadataPrefix);
        Record record = getRecord(id, format);
        ElementAppender.appendRecord(rootEl, record);
    }

    private Record getRecord(Identifier id, MetadataFormat format) throws OaiException, IOException {
        Repository repository = config.getRepository();
        Record record = repository.getRecord(id, format, true);
        if (record == null) {
            throw new OaiException(ErrorCode.cannotDisseminateFormat, "no such record");
        } else {
            return record;
        }
    }
}
